package com.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.MyEnum.NumberConstant;
import com.example.Utility.objIsNull;
import com.example.entity.ShoppingCar;
import com.example.mapper.ShoppingCarMapper;
import com.example.service.ShoppingCarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/shoppingCar")
public class ShoppingCarController {
    @Resource
    private ShoppingCarService shoppingCarService;
    @Autowired
    private ShoppingCarMapper shoppingCarMapper;


    /**
     * 根据id 删除
     *
     * @return Boolean
     */

    @GetMapping("/delete")
    public Boolean delete(Long id) {
        return shoppingCarService.removeById(id);
    }

    /**
     * 根据id 查询
     *
     * @return ShoppingCar。class
     */
    @GetMapping("get")
    public ShoppingCar get(Long id) {
        QueryWrapper<ShoppingCar> wrapper = new QueryWrapper<>();
        wrapper.eq("commodity_id", id);
        return shoppingCarMapper.selectById(id);
    }


    /**
     * 添加购物车 Boolean
     *
     * @param shoppingCar
     * @return Boolean
     */
    @PostMapping("/add")
    public Boolean add(@RequestBody ShoppingCar shoppingCar) {
        if (objIsNull.isNull(shoppingCar)) {
            throw new IllegalArgumentException("Invalid input: shoppingCar=" + shoppingCar);
        }
        LambdaQueryWrapper<ShoppingCar> shoppingCarQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCarQueryWrapper.eq(ShoppingCar::getOpenid, shoppingCar.getOpenid())
                .eq(ShoppingCar::getCommodityId, shoppingCar.getCommodityId());
        ShoppingCar existingShoppingCar = shoppingCarService.getOne(shoppingCarQueryWrapper);
        if (null == existingShoppingCar) {
            shoppingCar.setState(NumberConstant.ZERO);
            return shoppingCarService.save(shoppingCar);
        } else {
            String orderSum = String.valueOf(Integer.parseInt(shoppingCar.getOrderSum()) + Integer.valueOf(existingShoppingCar.getOrderSum()));
            existingShoppingCar.setOrderSum(orderSum);
            return shoppingCarService.updateById(existingShoppingCar);
        }
    }


    /**
     * 修改购物车
     *
     * @param shoppingCar
     * @return Boolean
     */
    @PostMapping("/update")
    public Boolean update(@RequestBody ShoppingCar shoppingCar) {
        QueryWrapper<ShoppingCar> queryWrapper = new QueryWrapper();
        queryWrapper.eq("commodity_id", shoppingCar.getCommodityId());
        return shoppingCarService.update(shoppingCar, queryWrapper);
    }

}
